package cn.com.dhcc.ddi.monitor.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import cn.com.dhcc.app.core.pubmodule.sysmgr.usermgr.service.CmUserMgrService;
import cn.com.dhcc.app.core.pubmodule.sysmgr.usermgr.vo.UserInfoVo;
import cn.com.dhcc.app.core.util.StrUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartSet;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartXmlUtil;
import cn.com.dhcc.ddi.datamapping.service.DataMappingService;
import cn.com.dhcc.ddi.datamapping.vo.DataMapping;
import cn.com.dhcc.ddi.datasource.service.DataSourceDBService;
import cn.com.dhcc.ddi.datasource.service.DataSourceService;
import cn.com.dhcc.ddi.datasource.vo.DataSourceVo;
import cn.com.dhcc.ddi.monitor.service.MonitorService;
import cn.com.dhcc.ddi.monitor.vo.DataSetVo;
import cn.com.dhcc.ddi.monitor.vo.EdgeVo;
import cn.com.dhcc.ddi.monitor.vo.TaskSuccessCountVo;
import cn.com.dhcc.ddi.task.service.TaskService;
import cn.com.dhcc.ddi.task.vo.Task;


/**
 * 监控controller
 * @日期：2016/12/12 09:51:22
 * @作者：李博宇
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("/monitor")
public class MonitorController extends BaseController{	
	@Autowired
	DataSourceService dataSourceService;
	@Autowired
	DataSourceDBService dataSourceDBService;
	@Autowired
	TaskService taskService;
	@Autowired
	MonitorService monitorService;
	@Autowired
	DataMappingService dataMappingService;
	@Autowired
	CmUserMgrService userMgrService;
	private static Logger logger = Log.getLogger(LOGTYPE.DDI);
	
	
	@RequestMapping("monitor_index")
	public String monitor(Model model,HttpSession httpSession){
		try {
			WhereCondition searchData = new WhereCondition();
			WhereCondition taskParameter = new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			if(!isAdmin){
				UserInfoVo currentUser = userMgrService.getUserById(userId);
				if(currentUser != null){
					searchData.where();
					String nodeIdsStr = currentUser.getExt2();
					WhereCondition dmParameter = new WhereCondition();
					dmParameter.where();
					if(StrUtil.isNotBank(nodeIdsStr)){
						String[] nodeIds = nodeIdsStr.split(",");
						dmParameter.in("t2.node_id", nodeIds);
						dmParameter.andIn("t3.node_id", nodeIds);
						searchData.in("t4.node_id",nodeIds);
					}else{
						dmParameter.eq("1", "2");
						searchData.eq("1", "2");
					}
					List<String> dmids = dataMappingService.getDmid(dmParameter);
					//过滤用户数据
					if (dmids!=null && dmids.size()>0){
						taskParameter.and().in("t1.mp_id",dmids);
					}else {
						taskParameter.and().eq("1","2");
					}
				}
			}
			List<DataSourceVo> dsList = monitorService.getDsStatus(searchData);
			
			//获取监控信息
			Map<String, Object> basicInfo = monitorService.getBasicInfo();
			
			//获取所有周期性任务
			List<Task> periodTaskList = taskService.getPeriodList(taskParameter);
			
			//获取周期性任务24小时统计
			List<List<String>> chartDatas = new ArrayList<List<String>>();
			for(Task task: periodTaskList) {
				List<TaskSuccessCountVo> countByHourList = monitorService.getTaskMonitorCount(task.getId());
				
				List<String> values = new ArrayList<String> ();
				for(TaskSuccessCountVo vo: countByHourList) {
					/*if(vo.getCount() != null) {
						values.add(vo.getCount());
					}*/
					values.add(vo.getCount());
				}
				chartDatas.add(values);
			}
			
			//获取交换关系图节点
			List<DataSetVo> dataSetList = new ArrayList<DataSetVo> ();
			for(DataSourceVo ds: dsList) {
				DataSetVo vo = new DataSetVo(ds.getId(), ds.getName());
				/*if(ds.getNeedAlert() != null && ds.getNeedAlert().equals("1")) {
					vo.setColor("red");
				} else {
					vo.setColor("green");
				}*/
				vo.setColor("#32dd6f");
				dataSetList.add(vo);
			}
			
			//获取交换关系图连线
			List<DataMapping> mapList = dataMappingService.getMappingList();
			List<EdgeVo> edgeList = new ArrayList<EdgeVo>();
			for(DataMapping dm: mapList) {
				EdgeVo edge = new EdgeVo(dm.getSrcDsId(), dm.getDestDsId());
				edgeList.add(edge);
			}
			
			
			/*for(int i = 0; i <30; i++) {
				DataSetVo vo = new DataSetVo(i+"", "node"+i);
				dataSetList.add(vo);
			}*/
			String dataSetJson = JsonUtil.toJson(dataSetList);
			String edgeJson = JsonUtil.toJson(edgeList);
			//String chartDataJson = JsonUtil.toJson(chartDatas);
			
			model.addAttribute("dsList", dsList);
			model.addAttribute("basicInfo", basicInfo);
			model.addAttribute("tasks", periodTaskList);
			model.addAttribute("chartDatas", chartDatas);
			model.addAttribute("dataSetList", dataSetJson);
			model.addAttribute("edgeList", edgeJson);
			return "monitor/monitor_index";
		} catch (Exception e) {
			logger.error("监控主页面加载失败", e);
		}
		
		return toAlertPage(model, "操作失败");
	}
	
	/**
	 * 获取统计图需要的数据
	 * @param ptaskId
	 * @return
	 * @throws ServiceException
	 */
	@ResponseBody
	@RequestMapping(value="/get_data", method = RequestMethod.POST)
	public Map<String,Object> generatChartData(String id, Model model) {
		try {			
			List<TaskSuccessCountVo> countByHourList = monitorService.getTaskMonitorCount(id);
			
			List<ChartSet> sets = new ArrayList<ChartSet>();
			for(TaskSuccessCountVo vo: countByHourList) {
				String label = "";
				String value = vo.getCount();
				ChartSet set = new ChartSet(label, value);
				sets.add(set);
			}
			 
			String xml = ChartXmlUtil.getXmlForOnlyLine(sets);
				
			return jsonSuccessDataResult("获取统计图", xml);
		} catch(ServiceException e) {
			logger.error(e);
			return jsonFailResult("获取统计图失败");
		}
	}
}
